package com.mgg.auth.authentication.openid;

import com.mgg.auth.service.user.UserService;
import com.mgg.common.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

@Component
@Primary
public class OpenIdUserDetailService implements UserDetailsService, SocialUserDetailsService{
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@Autowired
	private UserService userService;

	@Override
	public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
		logger.info("社交登录,userId = " + userId);
		try {
            UserVO userInfo = userService.getUserByUserId(userId);
            if (userInfo == null) {
                return null;
            }
            String username = userInfo.getUsername();
            String password = "";
            password = passwordEncoder.encode(password);
            String userStatus = userInfo.getUserStatus();
            Boolean accountNonLocked = true;
            if ("0".equals(userStatus)) {
                accountNonLocked = false;
            }
			return new SocialUser(userId, password,true,true,true,accountNonLocked,
					AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER,ROLE_ANONYMOUS"));
		} catch (Exception e) {
			e.printStackTrace();
			throw new UsernameNotFoundException("用户查询失败");
		}
	}

	@Override
	public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
		return null;
	}
}
